package com.prestamomo.vil.ppa.pmvilnet;


import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;

import com.prestamomo.vil.ppa.pmvilnet.pmvillistener.PmvilCallBack;
import com.prestamomo.vil.ppa.pmvilnet.pmvilutils.PmvilSimpObserver;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;

import org.jetbrains.annotations.NotNull;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class PmvilHttpCall {
    /**
     * @param pmvilOwner
     * @param pmvilObservable
     * @param pmvilCallBack
     * @param pmvilFlag
     * @param <T>
     */
    public static <T> void doPmvilCall(LifecycleOwner pmvilOwner, Observable<PmvilResponseModel<T>> pmvilObservable, final PmvilCallBack<T> pmvilCallBack, final String pmvilFlag) {

        if (pmvilObservable == null || pmvilCallBack == null) {
            throw new IllegalArgumentException("可观察或Callbacklis为空");
        }

        PmvilSimpObserver<PmvilResponseModel<T>> pmvilObserver = new PmvilSimpObserver<PmvilResponseModel<T>>() {

            @Override
            public void onNext(@NotNull PmvilResponseModel<T> pmvilResponseModel) {
                try {
                    if (pmvilResponseModel.getStatus().equals("200")) {
                        pmvilCallBack.onPmvilSucc(pmvilFlag, pmvilResponseModel.getBody());
                    }else if(pmvilResponseModel.getStatus().equals("301")){
                        pmvilCallBack.onPmvilLogOn(pmvilFlag,pmvilResponseModel.getBody());
                    } else {
                        pmvilCallBack.onPmvilOther(pmvilFlag, pmvilResponseModel.getBody(),pmvilResponseModel.getStatus(),pmvilResponseModel.getMessage());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    pmvilCallBack.onPmvilFailure(pmvilFlag, "誤差分析");
                }
            }

            @Override
            public void onError(Throwable pmvile) {
                pmvile.printStackTrace();
                pmvilCallBack.onPmvilFailure(pmvilFlag, PmvilHttpStatusCode.handlePmivlException(pmvile));
            }

        };

        if (pmvilOwner == null) {
            pmvilObservable.subscribeOn(Schedulers.newThread())
                    .unsubscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(pmvilObserver);
        } else {
            pmvilObservable.subscribeOn(Schedulers.newThread())
                    .unsubscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(pmvilOwner, Lifecycle.Event.ON_DESTROY)))
                    .subscribe(pmvilObserver);
        }
    }
}
